package com.code.monitor.controller;

import com.code.monitor.annotation.Controller;
import com.code.monitor.annotation.RequestMapping;
import com.code.monitor.annotation.RequestParam;
import com.code.monitor.annotation.ResponseBody;
import com.code.monitor.constants.OperateType;
import com.code.monitor.constants.ResultCode;
import com.code.monitor.constants.ResultEntity;
import com.code.monitor.model.CacheManager;
import com.code.monitor.model.MachineInfo;
import com.code.monitor.model.PackageInfo;
import com.code.monitor.service.MachineService;
import com.code.monitor.service.PackageService;
import com.code.monitor.utils.HttpUtils;
import com.code.monitor.utils.SSHUtils;
import com.code.monitor.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author ggh
 * @date 2023/5/8
 */
@Controller
@Slf4j
public class ServiceController {

    public static final int IP_DETECTION_TIMEOUT = 5000;
    public static final int SHUTDOWN_TIMEOUT = 5000;
    private static final int PORT = 18877;
    private static final String pingUri = "/autoTask/ping";
    private CopyOnWriteArraySet<String> arraySet = new CopyOnWriteArraySet<>();

    /**
     * 停止和启动接口
     *
     * @param ip
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/operate")
    public ResultEntity operate(@RequestParam("ip") String ip, @RequestParam(value = "port", require = false) Integer port, @RequestParam("type") Integer type) {
        try {
            if (OperateType.STOP.getType().equals(type) && port == null) {
                return ResultEntity.fail(ResultCode.PARAM_LACK);
            }
            OperateType operateType = OperateType.parse(type);
            boolean online = online(ip);

            if (arraySet.contains(ip)) {
                return ResultEntity.fail("已经点击过了");
            }
            arraySet.add(ip);
            log.info("{}机器的服务:{}", operateType.getMsg(), ip);

            boolean operateResult = false;
            if (OperateType.START.getType().equals(operateType.getType())) {
                if (online) {
                    arraySet.remove(ip);
                    return ResultEntity.fail(ip + ":已经启动");
                }

                MachineInfo machineInfo = SpringUtils.getBean(MachineService.class).queryMachineByIP(ip);
                PackageInfo packageInfo = SpringUtils.getBean(PackageService.class).queryPackageByUUID(machineInfo.getPackagejar());
                operateResult = SSHUtils.startRemoteServiceOnWindows(ip, machineInfo.getSshPort(), machineInfo.getUsername(), machineInfo.getPassword(), machineInfo.getSftpRoot(), packageInfo.getPath(), packageInfo.getFileName());
            } else if (OperateType.STOP.getType().equals(operateType.getType())) {
                if (!online) {
                    arraySet.remove(ip);
                    return ResultEntity.fail(ip + ":已经停止");
                }

                MachineInfo machineInfo = SpringUtils.getBean(MachineService.class).queryMachineByIP(ip);
                operateResult = SSHUtils.stopRemoteServiceOnWindows(ip, machineInfo.getSshPort(), machineInfo.getUsername(), machineInfo.getPassword(), machineInfo.getSftpRoot(), port);
            }

            arraySet.remove(ip);
            if (operateResult) {
                return ResultEntity.success(operateType.getMsg() + "成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            arraySet.remove(ip);
        }
        return ResultEntity.fail("操作失败");
    }

    /**
     * 停止和启动接口
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/test")
    public ResultEntity test() {
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultEntity.fail("操作失败");
    }

    private boolean online(String ip) {
        return CacheManager.getServiceInfoList().stream().anyMatch((serviceInfo) -> serviceInfo.getIp().contains(ip));
    }

    @RequestMapping(value = "/actuator")
    public String actuator(@RequestParam(value = "ip") String ip) {
        log.info("请求actuator信息:{}", ip);
        String result = HttpUtils.doGet("http://" + ip + ":" + PORT + pingUri, IP_DETECTION_TIMEOUT);
        return null;
    }
}
